//
//  NSString+Calculation.m
//  WSMallBuyer
//
//  Created by hedong on 2017/12/6.
//  Copyright © 2017年 hedong. All rights reserved.
//

#import "NSString+Calculation.h"

@implementation NSString (Calculation)

- (CGRect)calculateLabelRectWithWidth:(float)width fontsize:(float)fontsize {
    return [self calculateLabelRectWithSize:CGSizeMake(width, MAXFLOAT) font:Font(fontsize)];
}

- (CGRect)calculateLabelRectWithSize:(CGSize)size font:(UIFont *)font {
    NSDictionary *attributes = @{NSFontAttributeName : font};
    NSInteger options = NSStringDrawingUsesFontLeading | NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin;
    return [self boundingRectWithSize:size options:(NSStringDrawingOptions)options attributes:attributes context:nil];
}

- (CGRect)calculateLabelRectWithHeight:(float)height fontSize:(float)fontsize {
    return [self calculateLabelRectWithSize:CGSizeMake(MAXFLOAT, height) font:Font(fontsize)];
}

- (CGFloat)calculateLabelHeightWithWidth:(float)width fontsize:(float)fontsize {
    CGRect rect = [self calculateLabelRectWithSize:CGSizeMake(width, MAXFLOAT) font:Font(fontsize)];
    return ceil(rect.size.height);
}

- (int)charCount {
    int strlength = 0;
    char* p = (char*)[self cStringUsingEncoding:NSUnicodeStringEncoding];
    for (int i = 0; i < [self lengthOfBytesUsingEncoding:NSUnicodeStringEncoding]; i++) {
        if (*p) {
            p++;
            strlength++;
        } else {
            p++;
        }
    }
    return strlength;
}

@end
